import { useEffect, useState } from "react";
import { Input, Checkbox, Button, Spin } from "antd";
import { SearchOutlined, CloseOutlined } from "@ant-design/icons";
import { getStaffs } from "@/assets/js/networkRequest/method";
import Highlighter from "react-highlight-words";

// 当前可选择的用户
let userList: any = [];
// 全部用户
let totalUserList: any = [];
// 右边选择的用户
let selectedUsers: any = [];
// 是否全选
let allSelected: boolean = false;

let current: number = 1;
let pageCount: number = 0;
let requesting: boolean = true;

const QrAddUser = ({ setVisible, addUser, getAddUser, userType }: any) => {
  const [, setRender] = useState(0);
  let [serchKey, setSerchKey] = useState("");
  let [loding, setLoding] = useState(true);

  // 初始化数据
  const initData = () => {
    userList = [];
    totalUserList = [];
    selectedUsers = [];
    allSelected = false;
    current = 1;
    pageCount = 0;
    requesting = true;
  };

  // 将渲染的列表userList 和保存数据的列表totalUserList  初始化选择的成员
  const initUser = (user: any) => {
    selectedUsers = JSON.parse(JSON.stringify(user));
    userList.map((item: any) => {
      item.selected = false;
      user.map((addItem: any) => {
        if (item.uid === addItem.uid) {
          item.selected = true;
        }
      });
    });
    totalUserList.map((item: any) => {
      item.selected = false;
      user.map((addItem: any) => {
        if (item.uid === addItem.uid) {
          item.selected = true;
        }
      });
    });
    allSelected =
      selectedUsers.length === userList.length && userList.length ? true : false;
    setRender(Math.random() + 1);
  };

  // 根据当前页请求列表数据请求
  const requestListData = async () => {
    requesting = true;
    let res: any = await getStaffs({ current, limit: 50, follow_user: 1 });
    if (res.code === 200) {
      let { data } = res;
      pageCount = data.pageCount;
      let newlist = [...totalUserList, ...data.list];
      userList = newlist;
      totalUserList = JSON.parse(JSON.stringify(newlist));
      requesting = false;
      setLoding(false);
      initUser(addUser);
      setRender(Math.random() + 1);
    }
  };

  useEffect(() => {
    initData();
    requestListData();
  }, [userType]);

  useEffect(() => {
    initUser(addUser);
  }, [addUser]);

  // 名称搜索
  const serchUser = () => {
    if (!serchKey) {
      userList = JSON.parse(JSON.stringify(totalUserList));
    }
    userList = totalUserList.filter(
      (item: any) =>
        item.name.indexOf(serchKey) !== -1 || item.alias.indexOf(serchKey) !== -1
    );
    allSelected =
      selectedUsers.length === userList.length && userList.length ? true : false;
    setRender(Math.random() + 1);
  };

  // 选择成员
  const changeUser = ({ type, flag, uid }: any) => {
    // type 1 全选  2  删除一个  3  添加一个
    if (type === 1) {
      userList.map((item: any) => {
        item.selected = flag;
      });
      totalUserList.map((item: any) => {
        item.selected = flag;
      });
    } else if (type === 2) {
      userList.map((item: any) => {
        if (item.uid === uid) {
          item.selected = flag;
        }
      });
      totalUserList.map((item: any) => {
        if (item.uid === uid) {
          item.selected = flag;
        }
      });
    }
    selectedUsers = userList.filter((item: any) => item.selected);
    allSelected = selectedUsers.length === userList.length ? true : false;
    setRender(Math.random() + 1);
  };

  return (
    <div>
      <h2 className="dialog-title">添加成员</h2>
      <div className="flex overflow-hidden mb-24">
        <div className="w-280 flex flex-col border-r-1 border-solid border-grey-200">
          <div className="pr-32">
            <div className="w-260 bg-white rounded-sm mb-8">
              <Input
                prefix={
                  <SearchOutlined style={{ color: "#D3D3D3" }} onClick={serchUser} />
                }
                placeholder="请输入成员昵称"
                width={263}
                onPressEnter={serchUser}
                onChange={(e: any) => {
                  setSerchKey(e.target.value.trim());
                  if (!e.target.value) {
                    serchKey = "";
                    serchUser();
                  }
                }}
              />
            </div>

            <Checkbox
              checked={allSelected}
              onChange={(e: any) => {
                changeUser({ type: 1, flag: e.target.checked });
              }}>
              <span className="px-4 text-xs text-grey-600">
                全部成员({userList.length})
              </span>
            </Checkbox>
          </div>

          <div className="pt-10">
            <Spin spinning={loding}>
              <ul
                className="scrollY h-280 pr-20 overflow-y-auto"
                onScroll={(event: any) => {
                  /* 距离顶部100px，总页码大于当前页面，当前页面不是第一页，上次滚动请求完后 */
                  let scrollBottom =
                    event.target.scrollHeight -
                    event.target.scrollTop -
                    event.target.clientHeight;
                  if (scrollBottom < 36 && current < pageCount && !requesting) {
                    current += 1;
                    requestListData();
                  }
                }}>
                {userList.map((item: any) => {
                  return (
                    <li key={item.uid}>
                      <Checkbox
                        className="w-260 flex items-center justify-between flex-row-reverse mt-12 cursor-pointer select-none"
                        checked={item.selected}
                        onChange={(e: any) => {
                          changeUser({ type: 2, flag: e.target.checked, uid: item.uid });
                        }}>
                        <div className="flex items-center">
                          <img
                            alt=""
                            src={item.avatar}
                            className="rounded-2 mr-10 w-36 h-36"
                          />
                          <div className="flex flex-col items-start">
                            <span data-memberextid="YuShiKang">
                              <Highlighter
                                highlightStyle={{ color: "#1890ff" }}
                                searchWords={[serchKey]}
                                autoEscape
                                textToHighlight={item.name}
                              />
                            </span>
                            {serchKey && item.alias.indexOf(serchKey) !== -1 ? (
                              <span className="text-xs text-grey-300">
                                别名：
                                <span>
                                  <Highlighter
                                    highlightStyle={{
                                      color: "#1890ff",
                                    }}
                                    searchWords={[serchKey]}
                                    autoEscape
                                    textToHighlight={item.alias}
                                  />
                                </span>
                              </span>
                            ) : null}
                          </div>
                        </div>
                      </Checkbox>
                    </li>
                  );
                })}
                {current < pageCount && (
                  <Spin spinning={true}>
                    <li className="h-36" key="123"></li>
                  </Spin>
                )}
              </ul>
            </Spin>
          </div>
        </div>

        <div className="flex flex-1 flex-col pl-30">
          <p>已选成员({selectedUsers.length})</p>
          <ul className="scrollY h-340 overflow-y-auto pr-20">
            {selectedUsers.map((item: any) => {
              return (
                <li
                  key={item.uid}
                  className="w-240 cursor-pointer select-none flex items-center mt-12 justify-between">
                  <div className="flex flex-row items-center w-200 overflow-hidden">
                    <img alt="" src={item.avatar} className="rounded-2 mr-10 w-36 h-36" />
                    {item.name}
                  </div>
                  <div className="text-grey-600 cursor-pointer hover:opacity-80">
                    <CloseOutlined
                      onClick={() => {
                        changeUser({ type: 2, flag: false, uid: item.uid });
                      }}
                    />
                  </div>
                </li>
              );
            })}
          </ul>
        </div>
      </div>
      <div className="btn-wrap">
        <div className="left"></div>

        <div className="right">
          <Button
            key="back"
            onClick={() => {
              initUser(addUser);
              setVisible(false);
            }}>
            取消
          </Button>
          <Button
            key="submit"
            type="primary"
            onClick={() => {
              getAddUser(selectedUsers);
              setVisible(false);
            }}>
            确定
          </Button>
        </div>
      </div>
    </div>
  );
};

export default QrAddUser;
